import javax.swing.*;
import java.awt.*;

/**
 * @Author mao
 * @Date 2025/11/1
 * @Description JavaSwing开发的用户界面
 */

public class SwingLayout extends JFrame {
    private JTextField textField;
    private JButton button;
    private JTextArea textArea;
    private JComboBox<String> comboBox;

    public SwingLayout() {
        // 设置JFrame窗体
        setTitle("CUST实验课-Windows图形化界面设计");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 400);
        setLocationRelativeTo(null); //窗口居中显示
        setLayout(new BorderLayout()); // 设置窗口布局为BorderLayout

        // 北侧-文本框 + 按钮
        JPanel northPanel = new JPanel(new FlowLayout());
        textField = new JTextField(15);
        button = new JButton("添加");
        textField.setPreferredSize(new Dimension(170, 31));
        button.setPreferredSize(new Dimension(80, 29));

        textField.addActionListener(e
                -> processInput()); // 文本框回车事件
        button.addActionListener(e
                -> processInput()); // 按钮点击事件
        northPanel.add(textField);
        northPanel.add(button);
        add(northPanel, BorderLayout.NORTH);

        // 中间-文本区
        textArea = new JTextArea();
        textArea.setEditable(false); // 设置为只读
        JScrollPane scrollPane = new JScrollPane(textArea);
        add(scrollPane, BorderLayout.CENTER);

        // 南侧-下拉列表
        String[] options = {"Java", "I Love CUST", "Swing",
                "MySQL", "Redis", "SpringBoot", "Docker", "Git"};
        comboBox = new JComboBox<>(options);
        comboBox.addActionListener(e -> {
            String selected = (String) comboBox.getSelectedItem();
            textArea.append("选择: " + selected + "\n");
        });
        add(comboBox, BorderLayout.SOUTH);

        // 显示窗口
        setVisible(true);
    }

    private void processInput() {
        String input = textField.getText().trim();
        if (input.isEmpty()) {
            JOptionPane.showMessageDialog
                    (this, "输入内容不能为空！",
                            "提示", JOptionPane.WARNING_MESSAGE);
        } else if  (input.equalsIgnoreCase("clear")) {
            textArea.setText("");
        } else {
            textArea.append("输入: " + input + "\n");
        }
        textField.setText("");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SwingLayout::new);
    }
}